package msgbackend

import (
	"encoding/json"
	"fmt"
	"GoServer/database"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/name5566/leaf/log"
)

var rsContentchannel redis.Conn

type Channelconfiger struct {
	Sendtime int    `json:"sendTime"`
	Sender   string `json:"sender"`
}

//创建连接
func chanenlConnect() bool {
	g_JsonConfig := database.G_JsonConfig
	rs, err := redis.Dial("tcp", g_JsonConfig.RedisHost)
	_, err = rs.Do("AUTH", g_JsonConfig.RedisKey)
	if err != nil {
		log.Error("redis auth failed")
		return false
	}
	rsContentchannel = rs
	if err != nil {
		log.Error("redis connect failed: %v", err.Error())
		return false
	}
	log.Error("redis connect success")
	return true
}

func GetChannel() {
	if chanenlConnect() {
		go func() {
			for {
				getChannelMsg()
				// log.Debug("redis reconnecting")
				time.Sleep(time.Millisecond * 5)
			}
		}()
	}
}

func getChannelMsg() {
	g_JsonConfig := database.G_JsonConfig
	Channeltopic := g_JsonConfig.PrivatetopicAll.Gamechannel
	r, getErr := redis.String(rsContentchannel.Do("LPOP", Channeltopic))
	if getErr != nil {
		//log.Debug("LPOP err: %v", getErr.Error())
	}
	if r != "" {
		Msginfocache(r)
	}
}

func Msginfocache(data string) {
	var channelconfig Channelconfiger
	str := data
	err := json.Unmarshal([]byte(str), &channelconfig)
	if err == nil {
		fmt.Println(channelconfig.Sender)
		fmt.Println(channelconfig.Sendtime)
		g_JsonConfig := database.G_JsonConfig
		g_JsonConfig.PrivatetopicAll.Gateserver = channelconfig.Sender
		Channeltopic := g_JsonConfig.PrivatetopicAll.Gateserver
		fmt.Println(Channeltopic)
	} else {
		fmt.Println(err.Error())
	}
}
